<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Title</title>
    <link th:href="@{/css/bootstrap.min.css?v=3.3.7}" rel="stylesheet"/>
    <link rel="stylesheet" th:href="@{/css/plugins/layui/css/layui.css}">
    <style>
        body {
            padding: 10px;
        }

        .layui-form-item .layui-inline {
            margin: 10px 0px;
            padding-left: 15px;
        }

        #condition,#tableDiv {
            background: #fff;
        }

    </style>
</head>
<body>

<form id="condition">
    <div class="layui-form-item">
        <div class="layui-inline">
            <div class="layui-input-inline layui-input-wrap">
                <input type="text" placeholder="请输入学生名称" id="studentName" name="studentName" class="layui-input">
            </div>
            <button type="button" id="search" class="layui-btn">查询</button>
            <button type="reset" id="reset" class="layui-btn">重置</button>
        </div>
    </div>
</form>


<div style="padding: 16px;">
    <table class="layui-hide" id="test" lay-filter="test"></table>
</div>
<script type="text/html" id="toolbarDemo">
    <button class="layui-btn layui-btn-sm" lay-event="add">
        <i class="glyphicon glyphicon-plus"></i>
        新增</button>
    <button class="layui-btn layui-btn-sm" lay-event="update">
        <i class="glyphicon glyphicon-pencil"></i>
        编辑</button>
    <button class="layui-btn layui-btn-sm" lay-event="del">
        <i class="glyphicon glyphicon-remove"></i>
        删除</button>
    <button class="layui-btn layui-btn-sm" lay-event="getCheckData">获取选中行数据</button>
    <button class="layui-btn layui-btn-sm" lay-event="getData">获取当前页数据</button>
</script>
<script type="text/html" id="toolDemo">
    <div class="layui-clear-space">
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-xs" lay-event="more">
            更多
            <i class="layui-icon layui-icon-down"></i>
        </a>
    </div>
</script>
<script th:src="@{/js/plugins/layui/layui.js}"></script>
<script th:src="@{/js/jquery.min.js}"></script>
<script>
    var statusText = {
        '0': '在读',
        '1': '毕业'
    };

    var genderText = {
        '0': '男',
        '1': '女',
        '2': '保密'
    };
    function formatDate(dateStr) {
        // 假设 dateStr 是 "2002-11-02 00:00:00" 格式的字符串
        var date = new Date(dateStr);
        var year = date.getFullYear();
        var month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份是从0开始的
        var day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    }
    layui.use(function(){
        var table = layui.table;
        var dropdown = layui.dropdown;
        var $= layui.$;
        // 创建渲染实例
        table.render({
            elem: '#test',   //表格的id
            url: '/student/list', // 此处为静态模拟数据，实际使用时需换成真实接口
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', { // 右上角工具图标
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips',
                onClick: function(obj) { // 2.9.12+
                    layer.alert('自定义工具栏图标按钮');
                }
            }],

            css: [ // 重设当前表格样式
                '.layui-table-tool-temp{padding-right: 145px;}'
            ].join(''),
            cellMinWidth: 80,
            totalRow: true, // 开启合计行
            page: true,

            //thymeleaf 不允许2个中括号连起来
            cols: [
                [
                    {type: 'checkbox', fixed: 'left'},   //选择框
                    {field:'sid', fixed: 'left', title: 'ID', sort: true},
                    //field 里的值是类中的属性名称  title 代表列的标题
                    {field:'studentNum', title: '学号'},
                    {field:'studentName', title: '学生姓名'},
                    {field:'gender', title: '性别', templet: function(d){
                            return genderText[d.gender];
                        }},
                    {field:'age', title: '年龄'},
                    {field:'birthday', title: '生日', templet: function(d){
                            // 使用 formatDate 函数来格式化日期
                            return formatDate(d.birthday);
                        }},
                    {field:'className', title: '班级',templet:function (data){
                            if(!data.cla){
                                return '暂无班级';
                            }else{
                                return data.cla.className;
                            }
                        } },
                    {field:'hotelName', title: '宿舍号',templet:function (data){
                            if(!data.hotel){
                                return '暂无宿舍';
                            }else{
                                return data.hotel.hotelName;
                            }
                        } },
                    {field:'phone', title: '电话'},
                    {field:'email', title: '邮箱'},
                    {field:'homeAddress', title: '地址'},
                    {field:'emergencyContact', title: '紧急联系人姓名'},
                    {field:'emergencyContactPhone', title: '紧急联系人电话'},
                    {field:'majorName', title: '专业',templet:function (data){
                            if(!data.maj){
                                return '暂无专业';
                            }else{
                                return data.maj.majorName;
                            }
                        }},
                    {field:'status', title: '学生状态', templet: function(d){
                            return statusText[d.status];
                        }},
                    {field:'createBy', title: '创建人'},
                    {field: 'updateBy', title: '修改人'},
                    {field:'remark', title: '备注'},
                    {fixed: 'right', title:'操作', width: 134, minWidth: 125, templet: '#toolDemo'}
                ]
            ],
            error: function(res, msg){
                console.log(res, msg)
            }
        });


        // 工具栏事件
        table.on('toolbar(test)', function(obj){
            var id = obj.config.id;
            var checkStatus = table.checkStatus(id);
            var othis = lay(this);
            switch(obj.event){
                case 'add':
                    layer.open({
                        title: '添加学生',
                        type: 2,
                        area: ['70%','80%'],
                        content: '/student/toadd',
                        fixed: false, // 不固定
                        maxmin: true,
                        shadeClose: true,
                        btn: ['立即提交', '取消'],
                        btnAlign: 'c',
                        yes: function(index, layero){
                            // 获取 iframe 的窗口对象
                            var iframeWin =  window[layero.find('iframe')[0]['name']];
                            let studentNum = iframeWin.$('#studentNum');
                            let studentName = iframeWin.$('#studentName'); // 获得 iframe 中某个输入框元素
                            let gender = iframeWin.$('#gender'); // 获得 iframe 中某个输入框元素
                            let age = iframeWin.$('#age');
                            let birthday = iframeWin.$('#birthday'); // 获得 iframe 中某个输入框元素
                            let classId = iframeWin.$('#classId'); // 获得 iframe 中某个输入框元素
                            let hotelId = iframeWin.$('#hotelId');
                            let phone = iframeWin.$('#phone');
                            let email= iframeWin.$('#email');
                            let homeAddress = iframeWin.$('#homeAddress');
                            let emergencyContact = iframeWin.$('#emergencyContact');
                            let emergencyContactPhone = iframeWin.$('#emergencyContactPhone');
                            let majorId = iframeWin.$('#majorId');
                            let status = iframeWin.$('#status');
                            let createBy = iframeWin.$('#createBy');
                           // let createTime = new Date().toISOString();// 获取当前系统时间并转换为ISO字符串
                            let remark = iframeWin.$('#remark');
                            if($.trim(studentNum.val()) === '') {
                                // 显示获得的值
                                layer.msg('学号不能为空');
                                return studentNum.focus();
                            }
                            if($.trim(studentName.val()) === '') {
                                // 显示获得的值
                                layer.msg('姓名不能为空');
                                return studentName.focus();
                            }
                            if($.trim(gender.val()) === '') {
                                layer.msg('性别不能为空');
                                return gender.focus();
                            }
                            if($.trim(age.val()) === '') {
                                layer.msg('年龄不能为空');
                                return age.focus();
                            }

                            if($.trim(birthday.val()) === '') {
                                layer.msg('出生日期不能为空');
                                return birthday.focus();
                            }
                            if($.trim(classId.val()) === '') {
                                layer.msg('必须选择班级');
                                return classId.focus();
                            }
                            if($.trim(hotelId.val()) === '') {
                                layer.msg('必须选择宿舍');
                                return hotelId.focus();
                            }
                            if($.trim(phone.val()) === '') {
                                layer.msg('手机号不能为空');
                                return phone.focus();
                            }
                            if($.trim(email.val()) === '') {
                                layer.msg('邮箱不能为空');
                                return email.focus();
                            }
                            if($.trim(homeAddress.val()) === '') {
                                layer.msg('家庭住址不能为空');
                                return homeAddress.focus();

                            }
                            if($.trim(emergencyContact.val()) === '') {
                                layer.msg('紧急联系人不能为空');
                                return emergencyContact.focus();
                            }
                            if($.trim(emergencyContactPhone.val()) === '') {
                                layer.msg('紧急联系电话不能为空');
                                return emergencyContactPhone.focus();
                            }
                            if($.trim(majorId.val()) === '') {
                                layer.msg('专业不能为空');
                                return majorId.focus();
                            }
                            if($.trim(status.val()) === '') {
                                layer.msg('状态不能为空');
                                return status.focus();
                            }
                            if($.trim(createBy.val()) === '') {
                                layer.msg('创建人不能为空');
                                return createBy.focus();
                            }
                            $.ajax({
                                url: '/student/addSave',
                                type: 'post',
                                data: {
                                    studentNum: studentNum.val(),
                                    studentName: studentName.val(),
                                    gender: gender.val(),
                                    age: age.val(),
                                    birthday: birthday.val(),
                                    classId: classId.val(),
                                    hotelId: hotelId.val(),
                                    phone: phone.val(),
                                    email: email.val(),
                                    homeAddress: homeAddress.val(),
                                    emergencyContact: emergencyContact.val(),
                                    emergencyContactPhone: emergencyContactPhone.val(),
                                    majorId: majorId.val(),
                                    status: status.val(),
                                    createBy: createBy.val(),
                                    createTime: new Date().toISOString(),
                                    remark: remark.val()
                                },
                                dataType: 'json',
                                success: function(res) {
                                    layer.close(index);
                                    if(res.code === 0) {
                                        layer.msg(res.msg);
                                        //刷新表格
                                        table.reload('test');
                                    }
                                }
                            })
                        }
                    });
                    break;
                case 'update':
                    if(id == null) return layer.msg('请选择一行');
                    layer.open({
                        title: '编辑学生',
                        type: 2,
                        area: ['70%','80%'],
                        content: '/student/toupdate/'+checkStatus.data[0].sid,
                        fixed: false, // 不固定
                        maxmin: true,
                        shadeClose: true,
                        btn: ['立即提交', '取消'],
                        btnAlign: 'c',
                        yes: function(index, layero){
                            // 获取 iframe 的窗口对象
                            var iframeWin =  window[layero.find('iframe')[0]['name']];
                            let studentNum = iframeWin.$('#studentNum');
                            let studentName = iframeWin.$('#studentName'); // 获得 iframe 中某个输入框元素
                            let gender = iframeWin.$('#gender'); // 获得 iframe 中某个输入框元素
                            let age = iframeWin.$('#age');
                            let birthday = iframeWin.$('#birthday'); // 获得 iframe 中某个输入框元素
                            let classId = iframeWin.$('#classId'); // 获得 iframe 中某个输入框元素
                            let hotelId = iframeWin.$('#hid');
                            let phone = iframeWin.$('#phone');
                            let email= iframeWin.$('#email');
                            let homeAddress = iframeWin.$('#homeAddress');
                            let emergencyContact = iframeWin.$('#emergencyContact');
                            let emergencyContactPhone = iframeWin.$('#emergencyContactPhone');
                            let majorId = iframeWin.$('#major');
                            let status = iframeWin.$('#status');
                            let updateBy = iframeWin.$('#updateBy');
                            let remark = iframeWin.$('#remark');
                            if($.trim(studentNum.val()) === '') {
                                // 显示获得的值
                                layer.msg('学号不能为空');
                                return studentNum.focus();
                            }
                            if($.trim(studentName.val()) === '') {
                                // 显示获得的值
                                layer.msg('姓名不能为空');
                                return studentName.focus();
                            }
                            if($.trim(gender.val()) === '') {
                                layer.msg('性别不能为空');
                                return gender.focus();
                            }
                            if($.trim(age.val()) === '') {
                                layer.msg('年龄不能为空');
                                return age.focus();
                            }

                            if($.trim(birthday.val()) === '') {
                                layer.msg('出生日期不能为空');
                                return birthday.focus();
                            }
                            if($.trim(classId.val()) === '') {
                                layer.msg('必须选择班级');
                                return classId.focus();
                            }
                            if($.trim(hotelId.val()) === '') {
                                layer.msg('必须选择宿舍号');
                                return hotelId.focus();
                            }
                            if($.trim(phone.val()) === '') {
                                layer.msg('手机号不能为空');
                                return phone.focus();
                            }
                            if($.trim(email.val()) === '') {
                                layer.msg('邮箱不能为空');
                                return email.focus();
                            }
                            if($.trim(homeAddress.val()) === '') {
                                layer.msg('家庭住址不能为空');
                                return homeAddress.focus();

                            }
                            if($.trim(emergencyContact.val()) === '') {
                                layer.msg('紧急联系人不能为空');
                                return emergencyContact.focus();
                            }
                            if($.trim(emergencyContactPhone.val()) === '') {
                                layer.msg('紧急联系电话不能为空');
                                return emergencyContactPhone.focus();
                            }
                            if($.trim(majorId.val())===''){
                                layer.msg('专业不能为空');
                                return majorId.focus();
                            }
                            if($.trim(status.val()) === '') {
                                layer.msg('状态不能为空');
                                return status.focus();
                            }
                            if($.trim(updateBy.val()) === '') {
                                layer.msg('更新人不能为空');
                                return updateBy.focus();
                            }
                            $.ajax({
                                url: '/student/updateSave',
                                type: 'post',
                                data: {
                                    sid: checkStatus.data[0].sid,
                                    studentNum: studentNum.val(),
                                    studentName: studentName.val(),
                                    gender: gender.val(),
                                    age: age.val(),
                                    birthday: birthday.val(),
                                    classId: classId.val(),
                                    hotelId: hotelId.val(),
                                    phone: phone.val(),
                                    email: email.val(),
                                    homeAddress: homeAddress.val(),
                                    emergencyContact: emergencyContact.val(),
                                    emergencyContactPhone: emergencyContactPhone.val(),
                                    majorId: majorId.val(),
                                    status: status.val(),
                                    updateBy: updateBy.val(),
                                    updateTime: new Date().toISOString(),
                                    remark: remark.val()
                                },
                                dataType: 'json',
                                success: function(res) {
                                    layer.close(index);
                                    if(res.code === 0) {
                                        layer.msg(res.msg);
                                        //刷新表格
                                        table.reload('test');
                                    }
                                }
                            })
                        }
                    });
                    break;
                case 'del':
                    if(id == null) return layer.msg('请选择一行');
                    layer.confirm('确定删除吗？', function(index){
                        $.ajax({
                            url: '/student/delete/'+checkStatus.data[0].sid,
                            type: 'post',
                            dataType: 'json',
                            success: function(res) {
                                layer.close(index);
                                if(res.code === 0) {
                                    layer.msg(res.msg);
                                    table.reload('test');
                                }
                            }
                        })
                    });
            };
        });

        // 触发单元格工具事件
        table.on('tool(test)', function(obj){ // 双击 toolDouble
            var data = obj.data; // 获得当前行数据
            // console.log(obj)
            if(obj.event === 'edit'){
                layer.open({
                    title: '编辑 - id:'+ data.sid,
                    type: 1,
                    area: ['80%','80%'],
                    content: '<div style="padding: 16px;">自定义表单元素</div>'
                });
            } else if(obj.event === 'more'){
                // 更多 - 下拉菜单
                dropdown.render({
                    elem: this, // 触发事件的 DOM 对象
                    show: true, // 外部事件触发即显示
                    data: [{
                        title: '查看',
                        id: 'detail'
                    },{
                        title: '删除',
                        id: 'del'
                    }],
                    click: function(menudata){
                        if(menudata.id === 'detail'){
                            layer.msg('查看操作，当前行 ID:'+ data.id);
                        } else if(menudata.id === 'del'){
                            layer.confirm('真的删除行 [id: '+ data.id +'] 么', function(index){
                                obj.del(); // 删除对应行（tr）的DOM结构
                                layer.close(index);
                                // 向服务端发送删除指令
                            });
                        }
                    },
                    align: 'right', // 右对齐弹出
                    style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' // 设置额外样式
                })
            }
        });

        $("#search").click(function (){
            var studentName = $("#studentName").val();
            //var pass = $("#pass").val();
            var data = {studentName:studentName};
            table.reload('test',{
                where:data,
                page:{
                    curr:1
                }
            })
        })
        $("#reset").click(function (){
            table.reload('test',{
                where:{}
            });
        })
    });
</script>
</body>
</html>